package com.lu.library.base

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.hjq.bar.TitleBar
import com.lu.library.LogLifecycleObserver
import com.lu.library.R
import com.lu.library.widget.CommonTitleBarHelper
import me.shouheng.utils.permission.PermissionResultHandler
import me.shouheng.utils.permission.PermissionResultResolver
import me.shouheng.utils.permission.callback.OnGetPermissionCallback
import me.shouheng.utils.permission.callback.PermissionResultCallback


/**
 * Created by lyw.
 *
 */
abstract class BaseActivity<VB: ViewDataBinding> : AppCompatActivity(), PermissionResultResolver {


//    protected lateinit var viewModule :VM
    protected lateinit var binding: VB
    /**
     * 通用头部辅助类
     */
    protected lateinit var commonTitleBarHelper: CommonTitleBarHelper
    private var mActivityJumpTime: Long = 0

    /**
     *沉浸式状态栏
     */
    protected open var isApplySystemFits = true

    protected var mOnGetPermissionCallback : OnGetPermissionCallback?=null;

    override fun setOnGetPermissionCallback(onGetPermissionCallback: OnGetPermissionCallback?) {
        this.mOnGetPermissionCallback = onGetPermissionCallback
    }
    /**
     * 状态栏字体颜色黑色
     */
    open protected var statusBarDarkFont = true

    /**
     * 底部兼容nav高度
     */
    protected open var isAdjustNav = true
    protected override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(LogLifecycleObserver())
        binding = DataBindingUtil.setContentView(this,layoutResId())
//        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
//            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
//            insets
//        }

        ARouter.getInstance().inject(this)
        commonTitleBarHelper = CommonTitleBarHelper()
        commonTitleBarHelper.init(this)
        setNavigationBar()
        initViews()
        initListener()
        initData()
        if (isAdjustNav){
            adjustNavBar(binding.root)
        }

    }
    protected fun adjustNavBar(view:View){
        view.updatePadding(view.paddingLeft,view.paddingTop,view.paddingRight,BarUtils.getNavBarHeight())
    }
    protected open fun initListener(){

    }

//    abstract fun getViewModelClass():Class<VM>
    /**
     * 获取编辑框的内容（去除两边空格）
     *
     * @param editText
     * @return
     */
    fun getEditTextStr(editText: EditText): String {
        return editText.text.toString().trim { it <= ' ' }
    }

    override fun setTitle(titleId: Int) {
        commonTitleBarHelper.setTitle(titleId)
    }

    fun initLayout(style: Int) {
        commonTitleBarHelper.initLayout(style)
    }

    fun setRightOnClick(rightOnClick: View.OnClickListener?) {
        commonTitleBarHelper.setRightOnClick(rightOnClick)
    }

    override fun setTitle(titleId: CharSequence) {

        findViewById<View?>(R.id.titleBar)?.let { tittleBar->
            if (tittleBar is TitleBar){
                tittleBar.setTitle(titleId)
            }
        }
        commonTitleBarHelper.setTitle(titleId as String)


    }

    protected open fun initViews() {
    }

    /**
     * 设置沉浸式状态栏
     * 这个方法只适用于使用公共标题的情况下，个人情况下需要重新该方法
     */
    private fun setNavigationBar() {
//        ScreenUtil.setNavigationBar(this)
//        var titleBar = resources.getIdentifier("titleBar","id",packageName)
            findViewById<View?>(R.id.titleBar)?.let { tittleBar->
                if (tittleBar is TitleBar){
//                    tittleBar.setBackgroundResource(R.color.common_window_background_color)
                    tittleBar.leftView.setOnClickListener {
                        finish()
                    }
                }
                ImmersionBar.with(this)
                    .statusBarDarkFont(statusBarDarkFont)
                    .statusBarColor(R.color.transparent)
                    .titleBar(tittleBar)
                    .init() //必须调用方可应用以上所配置的参数
            }?:let {
                ImmersionBar.with(this)
                    .statusBarDarkFont(statusBarDarkFont)
                    .applySystemFits(isApplySystemFits)
                    .init() //必须调用方可应用以上所配置的参数
            }

    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    fun handleMessageInner(message: BaseMessage<*>?) {
//        handleMessage(message)
//    }
//
//    /**
//     * 子类如需处理EventBus发送的消息，重写此方法
//     * @param message 消息内容
//     */
//    protected fun handleMessage(message: BaseMessage<*>?) {
//    }



    /**
     * 检测权限，如果返回true,有权限 false 无权限
     * @param permissions 权限
     * @return 是否有权限
     */
//    fun checkSelfPermission(vararg permissions: String?): Boolean {
//        return PermissionUtil.checkSelfPermission(*permissions)
//    }
//
//    fun requestPermissions(requestCode: Int, vararg permissions: String?) {
//        PermissionUtil.requestPermissions(this, requestCode, *permissions)
//    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        permissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionResultHandler.handlePermissionsResult(this,requestCode,permissions,grantResults,object:
            PermissionResultCallback{
            override fun onGetAllPermissions() {
                mOnGetPermissionCallback?.onGetPermission()
            }

            override fun showPermissionsRationale(vararg permissions: String?) {
            }

            override fun onPermissionNotGranted(vararg permissions: String?) {

            }

        })
    }
    /**
     * 初始化数据
     */
    abstract fun initData()

    /**
     * 布局资源文件
     * @return 布局资源文件
     */
    abstract fun layoutResId(): Int



    /**
     * 跳转到Activity
     * @param clazz Activity类
     */
    protected fun startActivity(clazz: Class<*>?) {
        startActivityForResult(clazz, -1, null)
    }

    /**
     * 跳转到Activity，携带参数
     * @param clazz Activity类
     * @param bundle 数据
     */
    protected fun startActivity(clazz: Class<*>?, bundle: Bundle?) {
        startActivityForResult(clazz, -1, bundle)
    }

    /**
     * 开启一个activity并且自己销毁
     *
     * @param clazz
     */
    protected fun startActivityAndSelfFinish(clazz: Class<*>?) {
        startActivity(clazz)
        finish()
    }
    /**
     * startActivityForResult方式跳转到Activity
     * @param clazz Activity类
     * @param bundle 数据
     */
    /**
     * startActivityForResult方式跳转到Activity
     * @param clazz Activity类
     */
    protected fun startActivityForResult(
        clazz: Class<*>?,
        requestCode: Int,
        bundle: Bundle? = null
    ) {
        val intent: Intent = Intent(this, clazz)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        if (requestCode > 0) {
            startActivityForResult(intent, requestCode,null)
        } else {
            startActivity(intent)
        }
    }

    protected fun showToast(msg: String?) {
        ToastUtils.showShort(msg)
    }

    protected fun showToast(msg: Int) {
//        ToastUtil.showToast(IdoApp.getAppContext(), msg);
        ToastUtils.showShort(msg)
    }


}
